// package-store/pages/store-spokes-setting-apply/index.js
const app = getApp();
import { ManageTargetInfoUpdateMixins } from '../../../behaviors/page';
import { navBack, tipToast } from '../../../common/env';
import { obj2Arr, arr2Obj } from '../../../common/utils';
import { SPOKESMAN_APPLY_FIELD } from '../../../constants/manage';

Page({
    mixins: [ManageTargetInfoUpdateMixins],
    data: {
        fieldList: obj2Arr(SPOKESMAN_APPLY_FIELD),
        settingInfo: {},
        applyInfoFields: [],
        applyInfoFieldsMap: {},
    },
    onLoad(options) {
        app.event.addListener('sendSpokesSettingInfo', this._handleSendSettingInfo.bind(this));
    },
    onUnload() {
        app.event.removeListener('sendSpokesSettingInfo');
    },
    _handleSendSettingInfo(settingInfo) {
        const { applyInfoFields = ['nick_name', 'mobile'] } = settingInfo;
        this.setData({
            settingInfo,
            applyInfoFields,
            applyInfoFieldsMap: arr2Obj(applyInfoFields),
        });
    },
    handleChange(e) {
        const { value } = e.currentTarget.dataset;
        const { applyInfoFields, applyInfoFieldsMap } = this.data;
        const idx = applyInfoFields.indexOf(value);
        if (value && value != 'nick_name' && value != 'mobile') {
            applyInfoFieldsMap[value] ? applyInfoFields.splice(idx, 1) : applyInfoFields.push(value);
            this.setData({
                applyInfoFields,
                applyInfoFieldsMap: arr2Obj(applyInfoFields),
            });
        } else {
            tipToast('姓名与手机号为必填，无法取消');
        }
    },
    handleSave() {
        let { settingInfo, applyInfoFields } = this.data;
        if (applyInfoFields.length == 4) {
            applyInfoFields = ['nick_name', 'mobile', 'wechat_id', 'remark'];
        }
        settingInfo.applyInfoFields = applyInfoFields;
        app.event.trigger('getSpokesSettingInfo', settingInfo);
        navBack();
    },
})
